package com.personal.system.service.impl.content.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HtmlUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.personal.common.result.PageUtils;
import com.personal.common.result.Result;
import com.personal.model.system.SysUser;
import com.personal.system.config.SecurityUtil;
import com.personal.system.constant.MessageConstant;
import com.personal.system.entity.content.Article;
import com.personal.system.entity.content.Comment;
import com.personal.system.entity.vo.ApiArticleListVO;
import com.personal.system.entity.vo.ApiCommentListVO;
import com.personal.system.exception.GlobalException;
import com.personal.system.listener.SystemNoticeHandle;
import com.personal.system.mapper.content.ArticleMapper;
import com.personal.system.mapper.content.CommentMapper;
import com.personal.system.mapper.sys.SysUserMapper;
import com.personal.system.service.content.web.ApiCommentService;
import com.xxl.job.core.util.IpUtil;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ApiCommentServiceImpl implements ApiCommentService {

    private final CommentMapper commentMapper;

    private final SecurityUtil securityUtil;

    private final ArticleMapper articleMapper;

    private final SysUserMapper userMapper;

    @Override
    public Result insertComment(Comment comment) {
        String userId = securityUtil.checkLogin();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
        //获取ip地址
        String ip = IpUtil.getIp();
        String ipAddress = "192.168.1.1";
        String os = userAgent.getOperatingSystem().getName();
        if (os.contains("mac") || os.contains("Mac")) {
            comment.setSystem("mac");
        } else if (os.contains("Windows")) {
            comment.setSystem("windowns");
        }else {
            comment.setSystem("android");
        }

        //过滤内容 如删除html标签和敏感词替换
        String content = HtmlUtil.cleanHtmlTag(comment.getContent());
        comment.setContent(content);
        comment.setSystemVersion(os);
        comment.setIpAddress(ipAddress);
        comment.setUserId(securityUtil.getUserId().toString());
        int insert = commentMapper.insert(comment);
        if (insert == 0){
            throw new GlobalException(404,"评论失败");
        }

        String toUserId =  comment.getReplyUserId();
        int mark = toUserId == null ? 2 : 1;
        if (toUserId == null) {
            Article article = articleMapper.selectById(comment.getArticleId());
            toUserId =  article.getUserId();
        }
        // 发送系统通知
        SystemNoticeHandle.sendNotice(toUserId,MessageConstant.MESSAGE_COMMENT_NOTICE,
                MessageConstant.SYSTEM_MESSAGE_CODE,comment.getArticleId(),mark,comment.getContent());
        return Result.ok(comment);
    }

    @Override
    public Result selectCommentByArticleId(int pageNo, int pageSize, Long articleId) {
        //获取评论父级评论
        Page<ApiCommentListVO> pageList = commentMapper.selectCommentPage(new Page<>(pageNo,pageSize),articleId);
        //获取子级
        for (ApiCommentListVO vo : pageList.getRecords()) {
            List<Comment> commentList = commentMapper.selectList(
                    new LambdaQueryWrapper<Comment>().eq(Comment::getParentId, vo.getId()).orderByDesc(Comment::getCreateTime));
            for (Comment e : commentList) {
                SysUser sysUser = userMapper.selectById(e.getUserId());
                SysUser replyUserInfo = userMapper.selectById(e.getReplyUserId());
                ApiCommentListVO apiCommentListVO = ApiCommentListVO.builder()
                        .id(e.getId())
                        .userId(e.getUserId())
                        .replyUserId(e.getReplyUserId())
                        .nickname(sysUser.getUsername())
                        .replyNickname(replyUserInfo.getName())
//                        .replyWebSite(replyUserInfo.getWebSite())
                        .content(e.getContent())
                        .avatar(sysUser.getHeadUrl())
                        .createTimeStr(DateUtil.format(e.getCreateTime(),"yyyy-MM-dd HH:mm:ss"))
                        .browser(e.getBrowser())
                        .browserVersion(e.getBrowserVersion())
                        .system(e.getSystem())
                        .systemVersion(e.getSystemVersion())
                        .ipAddress(e.getIpAddress())
                        .build();
                vo.getChildren().add(apiCommentListVO);
            }
            vo.setCreateTimeStr(DateUtil.format(vo.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        return Result.ok(pageList);
    }

    @Override
    public Result selectMyComment() {
        Page<ApiArticleListVO> result  = commentMapper.selectMyComment(
                new Page<>(PageUtils.getPageNo(), PageUtils.getPageSize()),securityUtil.getUserIdWeb());
        return Result.ok(result);
    }
}
